/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let data = []
  const right = () => {
    const delArr = matrix.shift()

    data.push(...delArr)
  }
  const down = () => {
    matrix.forEach(item => {
      data.push(item.pop())
    })
  }
  const left = () => {
    const delArr = matrix.pop().reverse()
    data.push(...delArr)
  }
  const up = () => {
    const temArr = [...matrix]
    temArr.reverse().forEach(item => {
      data.push(item.shift())
    })
  }
  const wayArr = [right, down, left, up]
  const allLength = matrix.length * matrix[0].length
  let index = 0
  while (data.length !== allLength) {
    wayArr[index]()
    index++
    if (index === 4) {
      index = 0
    }
  }
  return data
}
console.log(
  spiralOrder([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ])
)
